<?php

namespace App\Models;

use App\Logic\Code;
use Illuminate\Auth\Authenticatable;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Tymon\JWTAuth\Contracts\JWTSubject;

/**
 * @author AdamTyn
 * @description <用户>数据模型
 */
class User extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject
{
    use Authenticatable, Authorizable;


    /**
     * 绑定数据表
     * @var string
     */
    protected $table = 'user';

    /**
     * 使用模型时可以访问的字段
     * @var array
     */
    protected $fillable = [
        'username', 'password',
    ];

    /**
     * 使用模型无法序列化为JSON时的字段
     * @var array
     */
    protected $hidden = [
        'password',
    ];

    /**
     * @author AdamTyn
     * @description 获取JWT中用户标识
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * @author AdamTyn
     * @description 获取JWT中用户自定义字段
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    private static $salt = 'user_power_salt';




    public static function login($data){


        $validateRule = [
            'username'                          => 'required',
            'password'                            => 'required',
        ];
        $errorMsg = [
            'username.required'                 => '账号不能为空',
            'password.required'                   => '密码不能为空',
        ];

        $validator = Validator::make($data, $validateRule, $errorMsg);
        if ($validator->fails()){
            $errors = $validator->errors()->all();
            return e_msg(300001,$errors[0]);
        }

        $pass = self::password($data['password']);
        $info1 = self::where('username',$data['username'])
            ->where('password',$pass)
            ->first();
        if($info1){
            $info = $info1;
        }else{
            $info = self::where('phone',$data['username'])
                ->where('password',$pass)
                ->first();
        }

        if($info){
            $auth = self::auth();
            if($token = $auth->login($info)){
                return s_msg('',[
                    'user_id' => $info->id,
                    'access_token' => $token,
                    'expires_in' => time()+86400,
                ]);
            }else{
                return e_msg(300001,'无法生成令牌');
            }
        }else{
            return e_msg(300003,'账号或密码不对');
        }

    }

    //注册
    public static function add($data){

        do {

            $username_front_two = GetUppers(2);
            $username_behind_eight = GetNumbers(8);
            $username = $username_front_two.$username_behind_eight;
            $re = self::where('username',$username)->value('id');

        } while ($re);

        $insert_arr = [
            'password' => self::password($data['password']),
            'nickname' => '矿工',
            'phone' => $data['phone'],
            'username' => $username,
        ];

        if($data['inviter']!=""){
            $inviter = self::where('username',$data['inviter'])->select('id','path','path_long','username','state')->first();
            if ( !$inviter ) {
                return e_msg(300005,'请核实邀请码');
            }
            if($inviter->state == 1){
                return e_msg(123456,'邀请人资质不符暂无邀请资格');
            }

            $insert_arr['pid'] = $inviter['id'];
            $insert_arr['path'] = $inviter['path'].$inviter['id'].',';
            $insert_arr['path_long'] = $inviter['path_long'] + 1;
            $insert_arr['inviter'] = $data['inviter'];
        }else{
            return e_msg(123456,'邀请码不能为空');
//            $insert_arr['path'] = '0,';
        }

        $rel = self::insertGetId($insert_arr);
        if($rel){
            return s_msg('');
        }else{
            return e_msg(300006,'注册失败,请联系网站客服');
        }
    }

    //设置手机号
    public static function phone($id,$phone){


        $user_id = self::where('id',$id)->value('username');
        if ( !$user_id ) {
            return e_msg(300015,'该用户不存在');
        }

        $update_arr = [
            'phone' => $phone,
        ];

        $rel = self::where('id',$id)->update($update_arr);

        if($rel){
            return s_msg('修改成功');

        }else{
            return e_msg(300016,'您没有作出修改');
        }
    }




    //重置密码
    public static function reset($id,$password){

        $user_id = self::where('id',$id)->value('username');
        if ( !$user_id ) {
            return e_msg(300015,'该用户不存在');
        }
        $update_arr = [
            'password' => self::password($password),
        ];
        $rel = self::where('id',$id)->update($update_arr);
        if($rel){
            return s_msg('重置成功');

        }else{
            return e_msg(300016,'重置成功');
        }
    }


    //重设密码
    public static function fog($data,$scene){

        $validateRule = [
            'phone'                          => 'required',
            'password'                            => 'required',
        ];
        $errorMsg = [
            'phone.required'                 => '手机号不能为空',
            'password.required'                   => '密码不能为空',
        ];

        $validator = Validator::make($data, $validateRule, $errorMsg);
        if ($validator->fails()){
            $errors = $validator->errors()->all();
            return e_msg(300001,$errors[0]);
        }


        $user_id = self::where('phone',$data['phone'])->value('id');
        if ( !$user_id ) {
            return e_msg(300015,'该手机号未注册');
        }


        $update_arr = [
            'password' => self::password($data['password']),
        ];

        $rel = self::where('id',$user_id)->update($update_arr);
        if($rel){
            return s_msg('');

        }else{
            return e_msg(300016,'您未做出修改');
        }
    }

    public function auth_user(){
        $auth = self::auth();
        if ($auth->check()) { # JWT同样可以使用Auth门面的check方法
            $data = $auth->user(); # JWT同样可以使用Auth门面的user方法
            return $data;
        } else {
            return e_msg(300007,'无法查询用户信息');
        }
    }

    public function logout(){
        $auth = self::auth();
        $auth->invalidate(true);

        return s_msg('');

    }

    public static function password($pass){

        return  sha1(self::$salt . $pass);

    }

    public static function auth(){

        return app('auth')->guard('api');
    }


    public static function import($arr,$brr = []){

        $pass = '123456';
        $password = self::password($pass);

        if(count($brr) > 0){
            $inviter = $brr['inviter'];
            $pid = $brr['pid'];
            $path = $brr['path'];
            $path_long = $brr['path_long'];
        }else{
            $inviter = 'FJ66589149';
            $pid = 100;
            $path = '0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,';
            $path_long = 100;
        }

        foreach($arr as $v){

            do {

                $username_front_two = GetUppers(2);
                $username_behind_eight = GetNumbers(8);
                $username = $username_front_two.$username_behind_eight;
                $re = self::where('username',$username)->value('id');

            } while ($re);

            $insert_arr = [
                'nickname' => $v['nickname'],
                'name' => $v['nickname'],
                'phone' => $v['mobile'],
                'username' => $username,
                'password' => $password,
                'is_import' => 1,
                'inviter' => $inviter,
                'pid' => $pid,
                'path' => $path,
                'path_long' => $path_long,
            ];
            $rel = DB::table('user')->insertGetId($insert_arr);
            if(count($v['children']) > 0) {
                $brr = [
                   'inviter' => $username,
                   'pid' => $rel,
                   'path' => $path.$rel.',',
                   'path_long' => $path_long + 1,

                ];
                self::import($v['children'],$brr);
            }

        }

    }


}
